package com.demo.datastructure.binarySearch;

/**
 * @author ljr
 * @version 1.0
 * @description: 查找第一个大于给定值的元素
 * @date 2021/10/13 17:25
 */
public class BinarySearch15 {

    public static int bsearch(int[] nums, int target) {
        int low = 0, high = nums.length-1, n =  high;
        while(low <= high){
            int mid = low + (high - low >> 1);
            if(nums[mid] >= target){
                if(mid == 0 || nums[mid -1] < target) return mid;
                else high = mid - 1;
            }else{
                low = mid + 1;
            }
        }
        return -1;
    }

    public static int bsearch2(int[] nums, int target) {
        int low = 0;
        int high = nums.length-1, n = high;
        while(low <= high) {
            int mid = low + (high - low >> 1);
            if(nums[mid] <= target){
                low = mid + 1;
            }else{
                high = mid - 1;
            }
        }
        if(high > 0 && high < n) return high+1;
        else return -1;
    }





    public static void main(String[] args) {
        //int[] nums = new int[]{1,3,5};
        int[] nums = new int[]{0,1,2,3,5,6,7,8,9};
        int index = BinarySearch15.bsearch2(nums,8);
        System.out.println(index);
    }

}
